<template>
  <a-card>
    <template #title>
      <a-form>
        <a-row :gutter="16">
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('员工姓名')">
              <a-input v-model:value="page.systemName"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('员工账号')">
              <a-input v-model:value="page.systemAccount"/>
            </a-form-item>
          </a-col>

          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('角色名称')">
              <a-select v-model:value="page.roleId" allowClear>
                <a-select-option v-for="item in roleList" :key="item.roleId" :value="item.roleId">{{
                    item.roleName
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('状态')">
              <a-select v-model:value="page.status" allowClear
                        :options="[{label:$t('启用'),value:1},{label:$t('禁用'),value:0}]"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('分单状态')">
              <a-select v-model:value="page.allotStatus" allowClear
                        :options="[{label:$t('启用'),value:1},{label:$t('禁用'),value:0}]"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('是否组长')">
              <a-select v-model:value="page.isLeader" allowClear
                        :options="[{label:$t('是'),value:1},{label:$t('否'),value:0}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <a-button type="primary" @click="addStaff" v-permiss="['add']">{{ $t('添加用户') }}</a-button>
    </div>
    <a-table row-key="systemId" :columns="tableColumn" :pagination="pagination" :data-source="tableData"
             :scroll="{x:1000}">
      <template #operation="{record }">
        <a-button type="link" @click="editStaff(record)" v-permiss="['update']">{{ $t('修改') }}</a-button>
        <a-button type="link" @click="resetPasswords(record)">{{ $t('重置密码') }}</a-button>
        <a-button type="link" @click="setOrderNum(record)">{{ $t('配置') }}</a-button>
        <a-button type="link" @click="setTargetAmount(record)">{{ $t('日目标') }}</a-button>
      </template>
      <template #status="{record }">
        <a-switch :checked="record.status === 1" @change="changeStatus(record)"></a-switch>
      </template>
      <template #allotStatus="{record}">
        <a-switch :checked="record.allotStatus === 1" @change="changeAllotStatus(record)"></a-switch>
      </template>
    </a-table>
    <a-modal v-model:visible="visible.isShow" :title="visible.title" :afterClose="clearForm" @ok="staffConfirm"
             :maskClosable="false">
      <a-form :rules="staffRulesForm" :model="staffForm" ref="formRef" :label-col="{span:5}">
        <a-form-item :label="$t('姓名')" name="systemName">
          <a-input v-model:value="staffForm.systemName"/>
        </a-form-item>

        <a-form-item :label="$t('账号')" name="systemAccount">
          <a-input v-model:value="staffForm.systemAccount" :disabled="visible.type === 'edit'"/>
        </a-form-item>
        <a-form-item label="whatsAPP" name="whatsApp">
          <a-input v-model:value="staffForm.whatsApp"/>
        </a-form-item>
        <a-form-item :label="$t('选择角色')" name="roleId">
          <a-select v-model:value="staffForm.roleId" :disabled="visible.type === 'edit'">
            <a-select-option v-for="item in roleList" :key="item.roleId" :value="item.roleId">
              {{ item.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('是否组长')" name="isLeader">
          <a-radio-group v-model:value="staffForm.isLeader" @change="changeIsLeader">
            <a-radio :value="1">{{ $t('是') }}</a-radio>
            <a-radio :value="0">{{ $t('否') }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item :label="$t('选择上级')" name="leaderId" v-if="staffForm.isLeader === 0">
          <a-select v-model:value="staffForm.leaderId" allowClear>
            <a-select-option v-for="item in leaderList" :key="item.systemId" :value="item.systemId">
              {{ item.systemName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('状态')" name="status">
          <a-radio-group v-model:value="staffForm.status">
            <a-radio :value="1">{{ $t('启用') }}</a-radio>
            <a-radio :value="2">{{ $t('禁用') }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item :label="$t('备注')">
          <a-textarea :rows="4" v-model:value="staffForm.remarks"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import {reactive, ref, toRefs, onMounted, computed, createVNode, watch} from 'vue'
import {
  fetchUserList,
  increaseUser,
  updateSystemUser,
  fetchRoleNameList,
  updateOrderNum,
  selectLeader
} from "../../../api/authority";
import {Input, message, Modal} from "ant-design-vue";
import locale from '@/locale';

const {t} = locale.global
const tableColumn = [
  {title: t('员工姓名'), dataIndex: 'systemName', width: 150, align: 'center'},
  {title: t('员工账号'), dataIndex: 'systemAccount', width: 100, align: 'center'},
  {title: 'whatsApp', dataIndex: 'whatsApp', width: 100, align: 'center'},
  {title: t('角色名称'), dataIndex: 'roleName', width: 100, align: 'center'},
  {
    title: t('是否组长'), dataIndex: 'isLeader', width: 100, align: 'center', customRender: ({text}) => {
      return text === 1 ? t('是') : t('否')
    }
  },
  {title: t('上级'), dataIndex: 'leaderName', width: 100, align: 'center'},
  {title: t('日目标金额'), dataIndex: 'target', width: 150, align: 'center'},
  {
    title: t('状态'), dataIndex: 'status', width: 100, align: 'center', slots: {customRender: 'status'}
  },
  {title: t('要单量'), dataIndex: 'allotOrderNum', width: 150, align: 'center'},
  {title: t('分单状态'), dataIndex: 'allotStatus', width: 100, align: 'center', slots: {customRender: 'allotStatus'}},
  {title: t('创建人'), dataIndex: 'inputName', width: 150, align: 'center'},
  {title: t('创建时间'), dataIndex: 'inputTime', width: 150, align: 'center'},
  {title: t('操作'), width: 200, align: 'center', fixed: 'right', slots: {customRender: 'operation',}},
]

export default {
  name: "UserManage",
  setup() {
    const formRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      visible: {
        isShow: false,
        type: '',
        title: ''
      },
      staffForm: {
        whatsApp: null,
        isLeader: 1,
        status: 1,
      },
      staffRulesForm: {
        systemName: [
          {required: true, message: t('不能为空'), trigger: 'blur'},
        ],
        systemAccount: [
          {required: true, message: t('不能为空'), trigger: 'blur'},
        ],
        roleId: [
          {required: true, message: t('不能为空'), trigger: 'change', type: 'number'},
        ],
      },
      tableData: [],
      roleList: [],
      leaderList: []
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total,
      onChange: (page) => {
        state.page.pageNum = page
        method.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        method.getTableData()
      }
    }))
    // watch(() => state.staffForm.isLeader, (value) => {
    //   state.staffForm.leaderId = null
    // })
    const method = {
      async getTableData() {
        const res = await fetchUserList(state.page)
        if (res.code === 1) {
          const {records, total} = res.data
          state.tableData = records
          state.page.total = total
        }
      },
      async getRoleList() {
        const res = await fetchRoleNameList()
        if (res.code === 1) {
          state.roleList = res.data
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        method.getTableData()
      },
      clearForm() {
        state.staffForm = {
          isLeader: 1,
          status: 1,
        }
        formRef.value.resetFields()
      },

      addStaff() {
        state.visible = {
          isShow: true,
          type: 'add',
          title: t('添加用户')
        }
        state.staffForm.status = 1
        state.staffForm.isLeader = 0
        method.getLeader()
        method.getRoleList()
      },
      changeIsLeader(value) {
        if (value === 1) {
          state.staffForm.leaderId = null
        }
      },
      editStaff(rows) {
        state.visible = {
          isShow: true,
          type: 'edit',
          title: t('编辑用户')
        }
        method.getRoleList()
        method.getLeader()
        state.staffForm = {
          ...rows,
          status: rows.status ? 1 : 2,
          usergroupId: rows.usergroupId,
          isLeader: rows.isLeader || 0
        }
        console.log(state.staffForm)
      },
      getLeader() {
        selectLeader().then(res => {
          state.leaderList = res.data
        })
      },
      staffConfirm() {
        formRef.value.validate().then(async () => {
          const api = ((params) => state.visible.type === 'add' ? increaseUser(params) : updateSystemUser(params))
          const params = {
            ...state.staffForm,
            roleName: state.roleList.find(r => r.roleId === state.staffForm.roleId).roleName
          }
          if (state.staffForm.leaderId) {
            params.leaderName = state.leaderList.find(item => item.systemId === state.staffForm.leaderId).systemName
          }
          if (state.staffForm.isLeader === 1) {
            params.leaderId = null
            params.leaderName = null
          }
          const res = await api(params)
          if (res.code === 1) {
            state.visible.isShow = false
            message.success(state.visible.type === 'add' ? t('添加成功') : t('编辑成功'))
            method.getTableData()
          }
        })
      },
      changeStatus({systemId, status}) {
        Modal.confirm({
          title: t('确认进行此操作') + '?',
          async onOk() {
            const res = await updateSystemUser({systemId, status: status === 1 ? 0 : 1})
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
        });
      },
      changeAllotStatus({systemId, allotStatus}) {
        Modal.confirm({
          title: t('确认进行此操作') + '?',
          async onOk() {
            const res = await updateSystemUser({systemId, allotStatus: allotStatus === 1 ? 0 : 1})
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
        });
      },
      setOrderNum({systemId, systemName, allotOrderNum}) {
        let text = allotOrderNum
        Modal.confirm({
          title: systemName + '-' + t('要单量设置'),
          content: createVNode(Input, {
            defaultValue: text,
            maxLength: 10,
            placeholder: t('每日自动分单上限'),
            onInput: (value) => {
              text = value.target.value
            },
            onKeyup: (value) => {
              value.target.value = value.target.value.replace(/[^\d]/g, '')
            }
          }),
          async onOk() {
            const res = await updateOrderNum({
              systemId, allotOrderNum: text
            })
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
        });
      },
      // 设置日目标金额
      setTargetAmount({systemId, systemName, target}) {
        let text = target
        Modal.confirm({
          title: systemName + '-' + t('日目标金额'),
          content: createVNode(Input, {
            defaultValue: text,
            maxLength: 10,
            placeholder: t('请输入'),
            onInput: (value) => {
              text = value.target.value
            },
            onKeyup: (value) => {
              value.target.value = value.target.value.replace(/[^\d]/g, '')
            }
          }),
          async onOk() {
            const res = await updateSystemUser({
              systemId, target: text
            })
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
        });
      },

      async resetPasswords({systemId, systemName}) {
        Modal.confirm({
          title: systemName + ' - ' + t('重置密码') + '?',
          content: t('重置密码后'),
          async onOk() {
            const res = await updateSystemUser({systemId, password: 123456})
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
        });
      }
    }
    onMounted(() => {
      method.getTableData()
      method.getRoleList()
    })
    return {
      tableColumn,
      formRef,
      pagination,
      ...method,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
